package com.ycode.bang.anbang;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.WindowManager;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.UsingFreqLimitedMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
import com.orhanobut.logger.LogLevel;
import com.orhanobut.logger.Logger;
import com.ycode.bang.anbang.activity.HomepageActivity;
import com.ycode.bang.anbang.activity.LoginActivity;
import com.ycode.bang.anbang.activity.LoginActivity2;
import com.ycode.bang.anbang.model.User;
import com.ycode.bang.anbang.utils.FileUtil;
import com.ycode.bang.anbang.utils.StringUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by ken on 2015/11/10.
 */
public class MyApp extends Application {

    private List<WeakReference<Activity>> activities = new ArrayList<WeakReference<Activity>>();
    public static List<Activity> apply = new ArrayList<Activity>();  //访单详情页相关
    public static String searchKeyword = "";
    public SharedPreferences mPreference;
    public static MyApp instance;
    private static String Token = "";
    public FileUtil fileUtil;
    private final String FILENAME = "anbang";
    public static ImageLoaderConfiguration config;
    public static DisplayImageOptions options;
    public ImageLoader imageLoader;
    public static User mUser = new User();
    public static String carTypeSelected = "";
    public static String carTypeIdSelected = "";
    // 屏幕宽度值。
    public int screenWidth;
    public int screenHeight;
    public static RequestQueue mRequestQueue;

    public static String carNumberCode = "";

    private File f;
    public String imagePath;

    private static String UserType = "";
    public static final String KEY_USER = "key_user";

    public HomepageActivity homepageActivity = null;

    public static String userNumber = "";

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        mPreference = PreferenceManager.getDefaultSharedPreferences(this);

        fileUtil = new FileUtil(this, FILENAME);
        File cacheDir = new File(fileUtil.sdPathStr + "/image");
        config = new ImageLoaderConfiguration.Builder(this).memoryCacheExtraOptions(1080, 1920)
                // max width, max height，即保存的每个缓存文件的最大长宽
//                .discCacheExtraOptions(1080, 1920, Bitmap.CompressFormat.JPEG, 100, null)
                // Can slow ImageLoader, use it carefully (Better don't use
                // it)/设置缓存的详细信息，最好不要设置这个
                .threadPoolSize(3)
                        // 线程池内加载的数量
                .threadPriority(Thread.NORM_PRIORITY - 2).denyCacheImageMultipleSizesInMemory()
                .memoryCache(new UsingFreqLimitedMemoryCache(8 * 1024 * 1024))
                        // You can pass your own memory cache
                        // implementation/你可以通过自己的内存缓存实现
                .memoryCacheSize(2 * 1024 * 1024).discCacheSize(50 * 1024 * 1024)
                .discCacheFileNameGenerator(new Md5FileNameGenerator())
                        // 将保存的时候的URI名称用MD5 加密
                .tasksProcessingOrder(QueueProcessingType.LIFO).discCacheFileCount(500)
                        // 缓存的文件数量
                .discCache(new UnlimitedDiscCache(cacheDir))
                        // 自定义缓存路径
                .defaultDisplayImageOptions(DisplayImageOptions.createSimple()).imageDownloader
                        (new BaseImageDownloader(this, 5 * 1000, 30 * 1000)).writeDebugLogs() //
                        // Remove for release app
                .build();// 开始构建
        ImageLoader.getInstance().init(config);// 全局初始化此配置
        imageLoader = ImageLoader.getInstance();
        options = new DisplayImageOptions.Builder().showImageOnLoading(R.drawable.icon_loadings)
                // 设置图片在下载期间显示的图片
                .showImageForEmptyUri(R.drawable.icon_loaderror)// 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.drawable.icon_loaderror) // 设置图片加载/解码过程中错误时候显示的图片
                .cacheInMemory(true)// 设置下载的图片是否缓存在内存中
                .cacheOnDisc(true)// 设置下载的图片是否缓存在SD卡中
                .considerExifParams(true) // 是否考虑JPEG图像EXIF参数（旋转，翻转）
                .imageScaleType(ImageScaleType.EXACTLY_STRETCHED)// 设置图片以如何的编码方式显示
                .bitmapConfig(Bitmap.Config.ARGB_8888)// 设置图片的解码类型//
                        // .delayBeforeLoading(int delayInMillis)//int
                        // delayInMillis为你设置的下载前的延迟时间
                        // 设置图片加入缓存前，对bitmap进行设置
                        // .preProcessor(BitmapProcessor preProcessor)
                .resetViewBeforeLoading(true)// 设置图片在下载前是否重置，复位
                        // .displayer(new RoundedBitmapDisplayer(20))// 是否设置为圆角，弧度为多少
                        // .displayer(new FadeInBitmapDisplayer(100))// 是否图片加载好后渐入的动画时间
                .build();// 构建完成
        // 得到手机屏幕宽度
        WindowManager wm = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
        screenWidth = wm.getDefaultDisplay().getWidth();
        screenHeight = wm.getDefaultDisplay().getHeight();

        Logger.init("VISIT")               // default PRETTYLOGGER or use just init()
                .setMethodCount(3)            // default 2
                .hideThreadInfo()             // default shown
                .setLogLevel(LogLevel.FULL);// default LogLevel.FULL

        mRequestQueue = Volley.newRequestQueue(this);

        // 保存分享的图片
        ApplicationInfo appInfo = getApplicationInfo();
        int resID = getResources().getIdentifier("ic_launcher", "mipmap",
                appInfo.packageName);
        saveMyBitmap(BitmapFactory.decodeResource(getResources(), resID));
        imagePath = MyApp.instance.fileUtil.sdPathStr + "/" + "logo.png";
    }

    public void setToken(String token) {
        Token = token;
        save(LoginActivity.KEY_TOKEN, token);
    }

    public void setUserType(String userType) {
        UserType = userType;
        save(KEY_USER, userType);
    }

    public String getToken() {
        Token = mPreference.getString(LoginActivity.KEY_TOKEN, "");
        return Token;
    }

    public String getUserType() {
        UserType = mPreference.getString(KEY_USER, "");
        return UserType;
    }

    public void addActivity(WeakReference<Activity> activity) {
        activities.add(activity);
    }

    public void removeActivity(WeakReference<Activity> activity) {
        activities.remove(activity);
    }

    public void exit() {
        try {
            for (WeakReference<Activity> activity : activities) {
                if (activity != null) activity.get().finish();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void loginOut() {
        try {
            int max=activities.size();
           for(int i=0;i<max;i++){
               WeakReference<Activity> activity  = activities.get(i);
                   if(i!=(activities.size()-1)){
                       if(activity!=null) {
                           activity.get().finish();
                       }
                   }else{
                       activities.clear();
                       Intent loginIntent  = new Intent(instance,LoginActivity2.class);
                       loginIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                       startActivity(loginIntent);
                       if(activity!=null) {
                           activity.get().finish();
                       }
                   }

           }
        } catch (Exception e) {
            e.printStackTrace();
        }
        MyApp.instance.setToken("");//放置token值
        MyApp.instance.setUserType("");//放置登录角色
    }

    public void save(String key, String value) {
        SharedPreferences.Editor edit = mPreference.edit();
        edit.putString(key, value);
        edit.commit();
    }

   public boolean isTokenEmpty(){
        return StringUtils.isEmpty(Token);
    }
    public void save(String key, boolean value) {
        SharedPreferences.Editor edit = mPreference.edit();
        edit.putBoolean(key, value);
        edit.commit();
    }

    public static boolean isManage() {//判断角色//是否为小区管理员
        if (MyApp.instance.getUserType().equals("1")) {
            return true;
        } else {
            return false;
        }

    }

    public static boolean isSuperManage() {//判断角色//是否为总管理员
        if (MyApp.instance.getUserType().equals("2")) {
            return true;
        } else {
            return false;
        }

    }

    public void save(String key, int value) {
        SharedPreferences.Editor edit = mPreference.edit();
        edit.putInt(key, value);
        edit.commit();
    }

    //清空保存的所有数据，用于退出登录
    public static void initData() {
        MyApp.instance.setToken("");
        mUser = new User();
        searchKeyword = "";
        carTypeSelected = "";
        carTypeIdSelected = "";
        carNumberCode = "";
    }

    // 保存图片到本地
    public void saveMyBitmap(Bitmap mBitmap) {
        File file = null;
        f = new File(file, MyApp.instance.fileUtil.sdPathStr + "/" + "logo.png");
        try {
            f.createNewFile();
        } catch (IOException e) {
            // TODO Auto-generated catch block
        }
        FileOutputStream fOut = null;
        try {
            fOut = new FileOutputStream(f);
        } catch (Exception e) {
            e.printStackTrace();
        }
        mBitmap.compress(
                Bitmap.CompressFormat.PNG,
                100, fOut);
        try {
            fOut.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fOut.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
